package leetcode.medium.q151;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
//        System.out.println("ni   jao j ".split(" ").length);
//        System.out.println("ni   jao j ".split("\\s+").length);
//        System.out.println(new Solution().reverseWords("ni   jao j "));
        System.out.println(new Solution3().reverseWords("  hello"));
    }

}

class Solution1 {
    public String reverseWords(String s) {
        if (s==null) {
            return null;
        }
        String[] strings = s.split("\\s+");
        StringBuilder sb = new StringBuilder();
        for (int i = strings.length-1; i >=0; i--) {
            sb.append(strings[i]).append(" ");
        }
        return sb.toString().trim();

    }
}
class Solution {
    public String reverseWords(String s) {
        if (s==null) {
            return null;
        }
        String[] strings = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for (int i = strings.length-1; i >=0; i--) {
            if (strings[i].length()==0)continue;
            sb.append(strings[i]).append(" ");
        }
        return sb.toString().trim();

    }
}
class Solution3 {
    public String reverseWords(String s) {
        if (s==null) {
            return null;
        }
        List<StringBuilder> words =new ArrayList<>(30);
        StringBuilder word =null;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i)==' ') {
                if (word!=null) {
                    words.add(word);
                    word=null;
                }
            }
            else {
                if (word==null) {
                    word = new StringBuilder().append(s.charAt(i));
                }else{
                    word.append(s.charAt(i));
                }
            }
        }
        StringBuilder res = new StringBuilder();
        if (word!=null){
            res.append(word).append(" ");
        }
        for (int i = words.size()-1; i >=0; i--) {
            res.append(words.get(i)).append(" ");
        }
        return res.deleteCharAt(res.length()-1).toString();
    }
}